package com.bjpowernode.crm.workbench.web.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.bjpowernode.crm.commons.constant.AppConstant;
import com.bjpowernode.crm.commons.enums.RespCode;
import com.bjpowernode.crm.commons.resp.Result;
import com.bjpowernode.crm.commons.utils.UUIDUtils;
import com.bjpowernode.crm.settings.domain.User;
import com.bjpowernode.crm.settings.service.UserService;
import com.bjpowernode.crm.workbench.domain.Activity;
import com.bjpowernode.crm.workbench.domain.ActivityRemark;
import com.bjpowernode.crm.workbench.service.ActivityRemarkService;
import com.bjpowernode.crm.workbench.service.ActivityService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.mysql.fabric.Response;
import com.sun.tools.javac.main.Main;
import jdk.nashorn.internal.ir.RuntimeNode;
import org.apache.poi.hssf.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.MulticastSocket;
import java.net.URLEncoder;
import java.util.*;

/**
 * ClassName:ActivityController
 * Package:com.bjpowernode.crm.workbench.web.controller
 * Date:2022/6/8 9:15
 * Description:
 * Author:zsm@zhangshuming.com
 */
@Controller
public class ActivityController {
    // 业务层接口
    @Autowired
    ActivityService activityService;
    @Autowired
    UserService userService;
    @Autowired
    ActivityRemarkService activityRemarkService;

    @RequestMapping("/workbench/activity/index.do")
    public String index(Model model) {
        List<User> userList = userService.queryAllUserList();
        model.addAttribute("userList", userList);
        return "/workbench/activity/index";
    }

    @RequestMapping("/workbench/activity/querActivityListPage.do")
    public @ResponseBody
    Object querActivityListPage(@RequestParam("pageNo") Integer pageNo,
                                @RequestParam("pageSize") Integer pageSize,
                                @RequestParam("activityName") String activityName,
                                @RequestParam("ownerName") String ownerName,
                                @RequestParam("startDate") String startDate,
                                @RequestParam("endDate") String endDate) {
        Result result = Result.FRR();
        try {
            // 准备查询条件
            Map<String, Object> param = new HashMap<>();
            param.put("activityName", activityName);
            param.put("ownerName", ownerName);
            param.put("startDate", startDate);
            param.put("endDate", endDate);

            /*
             *       使用PageHelper步骤
             * 使用pageHelper实现 分页、页码、每页显示条数
             *   1.设置分页的页码和每页显示数据
             *   2.调用业务逻辑层 获取市场活动列表数据（不要使用limit）
             *   3.pageHelper封装PageInfo对象信息
             * */
            // 设置分页页码和煤业显示次数
            PageHelper.startPage(pageNo, pageSize);
            // 按多条件分页查询市场活动列表数据结果
            List<Activity> activitielist = activityService.queryActivityListByCondition(param);
            // 使用pageHelp
            PageInfo<Activity> pageInfo = new PageInfo<>(activitielist);
            result = result.SUCCESS();
            if (ObjectUtil.isNull(pageInfo.getList()) || pageInfo.getList().size() == 0) {
                result.setRespCode(RespCode.QUER_NO_DATE);
            } else {
                result.setBody(pageInfo);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return result;
        }
        return result;
    }

    @RequestMapping("/workbench/activity/createActivityPage.do")
    @ResponseBody    public Object createActivityPage() {
        // 获取所有者列表数据
        List<User> userList = userService.queryAllUserList();
        return userList;
    }

    @RequestMapping("/workbench/activity/saveCreateActivityBtnPage.do")
    @ResponseBody
    public Result saveCreateActivityBtnPage(Activity activity, HttpServletRequest request) {
        Result result = Result.FRR();
        User user = (User) request.getSession().getAttribute(AppConstant.SESSION_USER);
        try {
            // 新增市场活动
            // 补全参数
            activity.setId(UUIDUtils.getUUID());
            activity.setCreateTime(DateUtil.formatDateTime(new Date()));
            activity.setCreateBy(user.getId());
            // 调用逻辑层
            activityService.saveCreateActivity(activity);
            result.setRespCode(RespCode.SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return result;
        }
        return result;
    }

    @RequestMapping("/workbench/activity/editActivityBtnPage.do")
    @ResponseBody
    public Result editActivityBtnPage(String id) {
        Result result = Result.FRR();
        try {
            // 根据id获得市场详情
            Activity activity = activityService.queryActivityById(id);

            result.setRespCode(RespCode.SUCCESS);
            if (ObjectUtil.isNull(activity)) {
                result.setRespCode(RespCode.QUER_NO_DATE);
            }
            result.setBody(activity);
        } catch (Exception e) {
            e.printStackTrace();
            return result;
        }
        return result;
    }

    @RequestMapping("/workbench/activity/saveEditActivityBtnPage.do")
    @ResponseBody
    public Result saveEditActivityBtnPage(HttpServletRequest request, Activity activity) {
        Result result = Result.FRR();
        // 完善对象信息
        User userSession = (User) request.getSession().getAttribute(AppConstant.SESSION_USER);
        try {
            // 更新市场活动信息
            activity.setEditTime(DateUtil.formatDateTime(new Date()));
            activity.setEditBy(userSession.getId());
            activityService.saveEditActivity(activity);
            result.setRespCode(RespCode.SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return result;
        }
        return result;
    }

    @RequestMapping("/workbench/activity/deleteActivityBtnPage.do")
    @ResponseBody
    public Result deleteActivityBtn(@RequestParam("id") String[] ids) {
        Result result = Result.FRR();
        try {
            //删除页面活动数据delete
            activityService.deleteActivityData(ids);
            result.setRespCode(RespCode.SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return result;
        }
        return result;
    }

    @RequestMapping("workbench/activity/exportActivityList.do")
    @ResponseBody
    public void exportActivityList(HttpServletRequest request, HttpServletResponse response) throws Exception {
        Map<String, Object> map = new HashMap<>();
        // 获取导出数据
        List<Activity> activities = activityService.queryActivityListByCondition(map);
        derivedData(response, activities);
        return;

    }
    // 导出数据
    private void derivedData(HttpServletResponse response, List<Activity> activities) throws IOException {
        // 创建excel表
        // 1.创建工作簿
        HSSFWorkbook workbook = new HSSFWorkbook();
        // 2.创建工作表
        HSSFSheet sheet = workbook.createSheet();
        // 3.创建行对象
        HSSFRow row = sheet.createRow(0);
        // 4.创建第一行第一列
        HSSFCell cell = row.createCell(0);
        cell.setCellValue("市场活动名称");
        cell = row.createCell(1);
        cell.setCellValue("所有者");
        cell = row.createCell(2);
        cell.setCellValue("开始日期");
        cell = row.createCell(3);
        cell.setCellValue("结束日期");

        // 循环创建行对象
        for (int i = 0; i < activities.size(); i++) {
            // 创建行对象
            row = sheet.createRow(i + 1);
            // 获取循环记录
            Activity activity = activities.get(i);
            // 创建列
            cell = row.createCell(0);
            cell.setCellValue(activity.getName());
            cell = row.createCell(1);
            cell.setCellValue(activity.getOwner());
            cell = row.createCell(2);
            cell.setCellValue(activity.getStartDate());
            cell = row.createCell(3);
            cell.setCellValue(activity.getEndDate());

        }
        //设置中文文件名称
        String fileName = URLEncoder.encode("市场活动列表", "UTF-8");
        //浏览器默认服务器传过去的是html，不是excel文件
        //设置响应类型:传输内容是流，并支持中文
        response.setContentType("application/octet-stream;charset=UTF-8");
        //设置响应头信息header，下载时以文件附件下载
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xls");
        //输出流对象
        OutputStream os = response.getOutputStream();
        workbook.write(os);
        //强制刷新
        os.flush();
        os.close();
        workbook.close();
    }

    // 选择导出
    @RequestMapping("/workbench/activity/exportActivityById")
    @ResponseBody
    public void exportActivityXzById(HttpServletRequest request,HttpServletResponse response,@RequestParam("id") String[] ids) throws IOException {
        List<Activity> list = activityService.queryActivityByIds(ids);
        derivedData(response,list);
        System.out.println("yes");
    }

    @RequestMapping("/workbench/activity/importActivityList.do")
    @ResponseBody
    public Result importActivityList(HttpServletRequest request, MultipartFile activityFile){
        Result result = Result.FRR();
        // 获得当前用户
        User userSession = (User) request.getSession().getAttribute(AppConstant.SESSION_USER);
        try {
            // 解析文件数据
            // 构建文件工作簿
            HSSFWorkbook wb = new HSSFWorkbook(activityFile.getInputStream());
            // 获取工作表
            HSSFSheet sheet = wb.getSheetAt(0);
            // 获取总行数
            int lastRowNum = sheet.getLastRowNum();
            // 创建行
            HSSFRow row = null;
            // 创建单元格
            HSSFCell cell = null;
            // 创建数组保存Activity对象
            List<Activity> activityList = new ArrayList<>();
            // 创建Activity对象保存值
            Activity activity = null;
            // 循环行
            for (int i = 1; i <= lastRowNum; i++) {
                activity = new Activity();
                activity.setId(UUIDUtils.getUUID());
                activity.setCreateTime(DateUtil.formatDateTime(new Date()));
                activity.setCreateBy(userSession.getId());
                // 行对象
                row = sheet.getRow(i);
                // 单元格对象
                cell = row.getCell(0);
                // 取出单元格中的值
                String activityName = cell.getStringCellValue();
                // 赋值到Activity中
                activity.setName(activityName);

                cell = row.getCell(1);
                String startDate = cell.getStringCellValue();
                activity.setStartDate(startDate);

                cell = row.getCell(2);
                String endDate = cell.getStringCellValue();
                activity.setEndDate(endDate);

                // 将所有的对象存放到数组中
                activityList.add(activity);
            }
            // 批量上传市场活动记录
            activityService.saveImportActivityList(activityList);
            result.setRespCode(RespCode.SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    @RequestMapping("workbench/activity/detail")
    public String detail(HttpServletRequest request,String id){
        Activity activity = activityService.queryActivityDetailById(id);
        request.setAttribute("activity", activity);
        return "workbench/activity/detail";
    }

    @RequestMapping("/workbench/activity/queryActivityRemarkListByActivityId.do")
    @ResponseBody
    public Result queryActivityRemarkListByActivityId(String activityId){
        Result result = Result.FRR();
        try {
            // 根据id查询备注信息
            List<ActivityRemark> activityRemark = activityRemarkService.queryActivityRemarkListByActivityId(activityId);
            result.setRespCode(RespCode.SUCCESS);
            if (activityRemark != null || activityRemark.size() != 0){
                result.setBody(activityRemark);
            }else {
                result.setRespCode(RespCode.QUER_NO_DATE);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return result;
        }
        return result;
    }

    @RequestMapping("/workbench/activity/saveCreateRemark.do")
    @ResponseBody
    public Result saveCreateRemark(HttpServletRequest request,ActivityRemark activityRemark){
        Result result = Result.FRR();
        // 获取当前市场活动id
        User userSession = (User) request.getSession().getAttribute(AppConstant.SESSION_USER);
        try {
            // 完善信息
            activityRemark.setId(UUIDUtils.getUUID());
            activityRemark.setCreateTime(DateUtil.formatDateTime(new Date()));
            activityRemark.setCreateBy(userSession.getId());
            // 发起请求
            activityRemarkService.saveCreateRemark(activityRemark);
            result.setRespCode(RespCode.SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return result;
        }
        return result;
    }

    @RequestMapping("/workbench/activity/updateRemarkBtn.do")
    @ResponseBody
    public Result updateRemarkBtn(HttpServletRequest request,ActivityRemark activityRemark){
        Result result = Result.FRR();
        User userSession = (User) request.getSession().getAttribute(AppConstant.SESSION_USER);
        try {
            // 完善对象信息
            activityRemark.setEditTime(DateUtil.formatDateTime(new Date()));
            activityRemark.setEditBy(userSession.getId());
            // 发起请求
            activityRemarkService.saveEditRemark(activityRemark);
            result.setRespCode(RespCode.SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return result;
        }
        return result;
    }


    @RequestMapping("/workbench/activity/deleteRemarkPage.do")
    @ResponseBody
    public Result delectRemarkPage(String remarkId){
        Result result = Result.FRR();
        try {
            // 删除市场活动详情备注信息
            activityRemarkService.deleteRemarkById(remarkId);
            result.setRespCode(RespCode.SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return result;
        }
        return result;
    }

}
